﻿using AspectCore.DynamicProxy;
using AspectCore.DynamicProxy.Parameters;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;
using Service.Core.Redis.Services;
using Service.Framework;
using System.Security.Claims;

namespace Service.Core.Redis.Aop.Cache
{
    /// <summary>
    /// 删除redis缓存拦截器
    /// </summary>
    public class RemoveRedisCacheInterceptorAttribute : DefaultInterceptor
    {
        private readonly string _cacheKey;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="cacheKey"></param>

        public RemoveRedisCacheInterceptorAttribute(string cacheKey)
        {
            _cacheKey = cacheKey;
        }

        public override int Order => 3;

        public override async Task Invoke(AspectContext context, AspectDelegate next)
        {
            var redisService = context.ServiceProvider.GetService<IRedisService>();
            if (redisService == null)
                throw new ArgumentNullException(nameof(redisService));
            var key = GetDefaultKey(context,_cacheKey);
            if (string.IsNullOrWhiteSpace(key))
            {
                throw new ArgumentNullException(nameof(key));
            }
            await next(context);
            if (await redisService.Database.KeyExistsAsync(key))
            {
                await redisService.Database.KeyDeleteAsync(key);
            }
        }
    }
}
